"use client"

import { useEffect, useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { AlertCircle } from "lucide-react"
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts"
import { getAllPolls, updatePollStatus, deletePoll } from "@/lib/db"

interface PollOption {
  id: string
  poll_id: string
  text: string
  votes: number
}

interface Comment {
  id: string
  poll_id: string
  text: string
  created_at: string
}

interface Poll {
  id: string
  title: string
  description: string
  active: boolean
  created_at: string
  options: PollOption[]
  poll_options?: PollOption[]
  comments?: Comment[]
}

export default function AdminPolls() {
  const [polls, setPolls] = useState<Poll[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetchPolls()
  }, [])

  const fetchPolls = async () => {
    try {
      setLoading(true)
      setError(null)

      console.log("Fetching all polls for admin...")
      const data = await getAllPolls()
      console.log("Fetched polls:", data)
      setPolls(data)
    } catch (error) {
      console.error("Error fetching polls:", error)
      setError("无法加载投票数据，请稍后再试")
    } finally {
      setLoading(false)
    }
  }

  const togglePollStatus = async (id: string, currentStatus: boolean) => {
    try {
      await updatePollStatus(id, !currentStatus)
      fetchPolls()
    } catch (error) {
      console.error("Error updating poll:", error)
      alert("更新失败，请重试")
    }
  }

  const handleDeletePoll = async (id: string) => {
    if (!confirm("确定要删除这个投票吗？此操作不可撤销。")) {
      return
    }

    try {
      await deletePoll(id)
      fetchPolls()
    } catch (error) {
      console.error("Error deleting poll:", error)
      alert("删除失败，请重试")
    }
  }

  if (loading) {
    return (
      <div className="space-y-6">
        {[1, 2].map((i) => (
          <Card key={i}>
            <CardHeader>
              <Skeleton className="h-6 w-3/4" />
              <Skeleton className="h-4 w-1/2 mt-2" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-[200px] w-full" />
            </CardContent>
            <CardFooter>
              <Skeleton className="h-10 w-full" />
            </CardFooter>
          </Card>
        ))}
      </div>
    )
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertDescription>{error}</AlertDescription>
      </Alert>
    )
  }

  if (polls.length === 0) {
    return (
      <Card>
        <CardContent className="text-center py-8">
          <p className="text-gray-500">暂无投票数据</p>
          <p className="text-sm text-gray-400 mt-2">创建一个新投票以开始</p>
        </CardContent>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      {polls.map((poll) => {
        // 确保 options 存在
        const options = poll.options || poll.poll_options || []

        // 创建图表数据
        const chartData = options.map((option) => ({
          name: option.text,
          votes: option.votes || 0,
        }))

        // 计算总票数
        const totalVotes = options.reduce((sum, option) => sum + (option.votes || 0), 0)

        return (
          <Card key={poll.id}>
            <CardHeader>
              <div className="flex justify-between items-start">
                <div>
                  <CardTitle>{poll.title}</CardTitle>
                  <CardDescription>{poll.description}</CardDescription>
                </div>
                {poll.active ? <Badge className="bg-green-500">进行中</Badge> : <Badge variant="outline">已结束</Badge>}
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="text-sm text-gray-500">
                创建于: {new Date(poll.created_at).toLocaleString()}
                <span className="ml-4">总票数: {totalVotes}</span>
              </div>

              {totalVotes > 0 ? (
                <div className="h-[250px] w-full">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={chartData} margin={{ top: 20, right: 30, left: 20, bottom: 60 }}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="name" angle={-45} textAnchor="end" height={60} interval={0} />
                      <YAxis allowDecimals={false} />
                      <Tooltip />
                      <Bar dataKey="votes" fill="#8884d8" />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              ) : (
                <div className="text-center py-4 text-gray-500">暂无投票数据</div>
              )}

              <div className="grid grid-cols-2 gap-4">
                {options.map((option) => (
                  <div key={option.id} className="flex justify-between items-center p-2 border rounded">
                    <span>{option.text}</span>
                    <span className="font-medium">{option.votes || 0} 票</span>
                  </div>
                ))}
              </div>
            </CardContent>
            <CardFooter className="flex justify-between">
              <div className="flex items-center space-x-2">
                <Switch
                  id={`active-${poll.id}`}
                  checked={poll.active}
                  onCheckedChange={() => togglePollStatus(poll.id, poll.active)}
                />
                <Label htmlFor={`active-${poll.id}`}>{poll.active ? "开启中" : "已关闭"}</Label>
              </div>
              <Button variant="destructive" onClick={() => handleDeletePoll(poll.id)}>
                删除投票
              </Button>
            </CardFooter>
          </Card>
        )
      })}
    </div>
  )
}
